import 'package:flutter/material.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:yysk_app/widget/button_widget.dart';

class RegionPicker extends StatefulWidget {
  final List<dynamic> provinces;
  final String? initialProvince;
  final String? initialCity;
  final String? initialDistrict;
  final int level; // 1: 仅省份, 2: 省份+城市, 3: 省份+城市+区县
  final Function(LevelModel) callback;
  const RegionPicker({
    super.key,
    required this.provinces,
    this.initialProvince,
    this.initialCity,
    this.initialDistrict,
    this.level = 2, required this.callback, // 默认为三级联动
  });

  @override
  State<RegionPicker> createState() => _RegionPickerState();
}


class LevelModel {
  String? province;
  String? provinceId;
  String? city;
  String? cityId;
  String? district;
  String? districtId;

  LevelModel({this.province, this.provinceId, this.city, this.cityId, this.district, this.districtId});

  LevelModel.fromJson(Map<String, dynamic> json) {
    province = json["province"];
    provinceId = json["provinceId"];
    city = json["city"];
    cityId = json["cityId"];
    district = json["district"];
    districtId = json["districtId"];
  }

  static List<LevelModel> fromList(List<Map<String, dynamic>> list) {
    return list.map(LevelModel.fromJson).toList();
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> _data = <String, dynamic>{};
    _data["province"] = province;
    _data["provinceId"] = provinceId;
    _data["city"] = city;
    _data["cityId"] = cityId;
    _data["district"] = district;
    _data["districtId"] = districtId;
    return _data;
  }
}
class _RegionPickerState extends State<RegionPicker> {
  late String? selectedProvince;
  late String? selectedCity;
  late String? selectedDistrict;
  String selectedProvinceId='';
  String selectedCityId='';
  String selectedDistrictId='';
  
  List<dynamic> cities = [];
  List<dynamic> districts = [];

  @override
  void initState() {
    super.initState();
    selectedProvince = widget.initialProvince;
    selectedCity = widget.initialCity;
    selectedDistrict = widget.initialDistrict;
    
    // 初始化城市数据（如果是二级或三级联动）
    if (selectedProvince != null && widget.level >= 2) {
      final province = widget.provinces.firstWhere(
        (p) => p['name'] == selectedProvince,
        orElse: () => null,
      );
      if (province != null && province['children'] != null) {
        cities = province['children'] is List ? province['children'] : [];
      }
    }
    
    // 初始化区县数据（如果是三级联动）
    if (selectedCity != null && cities.isNotEmpty && widget.level == 3) {
      final city = cities.firstWhere(
        (c) => c['name'] == selectedCity,
        orElse: () => null,
      );
      if (city != null && city['children'] != null) {
        districts = city['children'] is List ? city['children'] : [];
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.8,
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
      ),
      padding: const EdgeInsets.all(20),
      child: Column(
        children: [
          // 标题和关闭按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '选择地区',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
              IconButton(
                icon: const Icon(Icons.close),
                onPressed: () => Navigator.pop(context),
              ),
            ],
          ),
          const SizedBox(height: 10),
          
          // 当前选择显示
          Container(
            padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
            decoration: BoxDecoration(
              color: Colors.blue[50],
              borderRadius: BorderRadius.circular(12),
            ),
            child: Row(
              children: [
                const Icon(Icons.check_circle, color: AppColors.fontColorGreen, size: 18),
                const SizedBox(width: 10),
                Text(
                  selectedProvince != null
                      ? '$selectedProvince${selectedCity != null ? ' > $selectedCity' : ''}${selectedDistrict != null && widget.level == 3 ? ' > $selectedDistrict' : ''}'
                      : '请选择地区',
                  style: const TextStyle(fontSize: 16),
                ),
              ],
            ),
          ),
          
          const SizedBox(height: 20),
          
          // 三级联动区域
          Expanded(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 省份列表（始终显示）
                _buildRegionList(
                  title: '省份',
                  items: widget.provinces.map((p) => {'name':p['name'] as String ,'code':p['code'] as String}).toList(),
                  selectedItem: selectedProvince,
                  onSelected: (province,provinceId) {
                    setState(() {
                      selectedProvince = province;
                      selectedProvinceId = provinceId;
                      selectedCity = null;
                      selectedDistrict = null;
                      
                      final p = widget.provinces.firstWhere(
                        (p) => p['name'] == province,
                        orElse: () => null,
                      );
                      
                      // 根据联动级别决定是否加载城市数据
                      if (widget.level >= 2 && p != null && p['children'] != null) {
                        cities = p['children'] is List ? p['children'] : [];
                      } else {
                        cities = [];
                      }
                      
                      districts = [];
                    });
                  },
                ),
                
                // 城市列表（二级或三级联动时显示）
                if (cities.isNotEmpty && widget.level >= 2)
                  _buildRegionList(
                    title: widget.level == 3 ? '城市' : '地区',
                    items: cities.map((c) => {'name':c['name'] as String ,'code':c['code'] as String}).toList(),
                    selectedItem: selectedCity,
                    onSelected: (city,cityId) {
                      setState(() {
                        selectedCity = city;
                        selectedCityId = cityId;
                        selectedDistrict = null;
                        
                        final c = cities.firstWhere(
                          (c) => c['name'] == city,
                          orElse: () => null,
                        );
                        
                        // 如果是三级联动，加载区县数据
                        if (widget.level == 3 && c != null && c['children'] != null) {
                          districts = c['children'] is List ? c['children'] : [];
                        } else {
                          districts = [];
                        }
                      });
                    },
                  ),
                
                // 区县列表（仅三级联动时显示）
                if (widget.level == 3)
                  _buildRegionList(
                    title: '区县',
                    items: districts.map((d) => {'name':d['name'] as String ,'code':d['code'] as String}).toList(),
                    selectedItem: selectedDistrict,
                    onSelected: (district,districtId) {
                      setState(() {
                        selectedDistrict = district;
                        selectedDistrictId  = districtId;
                      });
                    },
                  ),
              ],
            ),
          ),
          
          const SizedBox(height: 20),
          // 确定按钮
          Center(
            child: ButtonWidget(
              label: "确定",
              width: 322.px,
              height: 54.px,
              fontSize: 18.px,
              imageBg: 'static/images/btm.png',
              contentType: ContentType.other,
              onPressed: () {
                // selectedProvince != null && 
                //         (widget.level == 1 || 
                //          (widget.level == 2 && selectedCity != null) ||
                //          (widget.level == 3 && selectedCity != null && selectedDistrict != null))
                //   ? () => Navigator.pop(context, {
                //         'province': selectedProvince,
                //         'city': widget.level >= 2 ? selectedCity : null,
                //         'district': widget.level == 3 ? selectedDistrict : null,
                //       })
                //   : null;
                
                  //  Navigator.pop(context, {
                  //       'province': selectedProvince,
                  //       'city': widget.level >= 2 ? selectedCity : null,
                  //       'district': widget.level == 3 ? selectedDistrict : null,
                  //     });
                if(widget.level == 1){
                 widget.callback(LevelModel(province: selectedProvince,city:selectedCity,district: selectedDistrict,provinceId: selectedProvinceId??'',cityId: selectedCityId??'',districtId: selectedDistrictId??''));
                }else if(widget.level == 2){
                  widget.callback(LevelModel(province: selectedProvince,city:selectedCity,district: selectedDistrict,provinceId: selectedProvinceId??'',cityId: selectedCityId??'',districtId: selectedDistrictId??''));
                }else{
                   widget.callback(LevelModel(province: selectedProvince,city:selectedCity,district: selectedDistrict,provinceId: selectedProvinceId??'',cityId: selectedCityId??'',districtId: selectedDistrictId??''));
                }
                 Navigator.pop(context);
              },
            ),
          ),
       ],
      ),
    );
  }

  // 构建区域列表组件
  Widget _buildRegionList({
    required String title,
    required List<dynamic> items,
    required String? selectedItem,
    required Function(String,String) onSelected,
  }) {
    return Expanded(
      child: Container(
        margin: const EdgeInsets.only(right: 8),
        decoration: BoxDecoration(
          color: AppColors.backgroundColor,
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.all(12.0),
              child: Text(
                title,
                style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
              ),
            ),
            const Divider(height: 1),
            Expanded(
              child: ListView.builder(
                itemCount: items.length,
                itemBuilder: (context, index) {

                  final item = items[index]['name'];
                  return InkWell(
                    onTap: () => onSelected(items[index]['name'],items[index]['code']),
                    child: Container(
                      padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 16),
                      decoration: BoxDecoration(
                        color: selectedItem == item ? Colors.blue[50] : Colors.transparent,
                        border: Border(
                          bottom: BorderSide(color: Colors.grey[200]!),
                        ),
                      ),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text(
                              item,
                              style: TextStyle(
                                color: selectedItem == item ? AppColors.fontColorGreen : Colors.black,
                                fontWeight: selectedItem == item ? FontWeight.bold : FontWeight.normal,
                              ),
                            ),
                          ),
                          if (selectedItem == item)
                            const Icon(Icons.check, color: AppColors.fontColorGreen, size: 18)
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
